package com.jgp.security.service;

import com.jgp.security.secmodel.SecResource;
import com.jgp.security.secmodel.SecRole;
import com.jgp.security.secmodel.SecRoleResource;
import com.jgp.security.secrepository.SecResourceRepository;
import com.jgp.security.secrepository.SecRoleResourceRepository;
import com.jgp.sys.query.Operator;
import com.jgp.sys.query.QueryFilterList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-11-02
 */
@Service
@Transactional(transactionManager = "secondTransactionManager", readOnly = true)
public class SecRoleResourceService {
    
    @Lazy
    @Autowired
    private SecRoleResourceRepository repository;
    @Lazy
    @Autowired
    private SecResourceRepository resourceRepository;
    
    public List<String> queryResourceIds(List<Long> roles) {
        List<SecRoleResource> roleResources = repository.findByRoleIdIn(roles);
        return roleResources.stream().map(SecRoleResource::getResourceId).distinct().collect(Collectors.toList());
    }
    
    /**
     * 查询资源
     *
     * @param roles 角色对象集合
     * @return
     */
    public List<SecResource> queryResources(List<SecRole> roles) {
        List<String> ids = queryResourceIds(roles.stream().map(SecRole::getId).collect(Collectors.toList()));
        return resourceRepository.read(ids);
    }
    
    /**
     * 查询资源动作标识
     *
     * @param roles roles 角色对象集合
     * @return
     */
    public List<String> queryResourceActions(List<Long> roles) {
        List<SecRoleResource> roleResources = repository.findByRoleIdIn(roles);
        List<String> ids = roleResources.stream().map(SecRoleResource::getResourceId).collect(Collectors.toList());
        return resourceRepository.read(ids).stream().map(SecResource::getAction).distinct().collect(Collectors.toList());
    }
    
    public List<String> queryResourceIds(Long roleId) {
        QueryFilterList filters = new QueryFilterList();
        return repository.read(filters).stream().map(SecRoleResource::getResourceId).collect(Collectors.toList());
    }
    
    @Transactional
    public void addRoleRes(Long roleId, String resId) {
        SecRoleResource roleRes = new SecRoleResource();
        roleRes.setRoleId(roleId);
        roleRes.setResourceId(resId);
        repository.create(roleRes);
    }
    
    @Transactional
    public void removeRoleRes(Long roleId, String resId) {
        QueryFilterList filters = new QueryFilterList();
        filters.addFilter("roleId", Operator.eq, roleId);
        filters.addFilter("resourceId", Operator.eq, resId);
        repository.deletePersist(filters);
    }
}
